package com.wangshouyu.mp.system.sign;

import com.google.common.io.ByteStreams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static com.wangshouyu.mp.base.request.ResponseBody.UTF_8;


/**
 * @author wangshouyu
 * 微信签名工具类
 */
public class MpSign {

	private static final Logger log = LoggerFactory.getLogger(MpSign.class);

	/**
	 * 输入流转字符串
	 * @param inputStream 输入流
	 * @return 字符串
	 */
	public static String format(InputStream inputStream){
		try {
			return new String(ByteStreams.toByteArray(inputStream), UTF_8);
		} catch (IOException e) {
			log.error("read input stream fail", e);
		}
		return null;
	}

	/**
	 * 签名校验
	 * @param signInfo 签名
	 * @param token token
	 * @return 是否校验成功
	 */
	public static boolean checkSignature(MpSignInfo signInfo, String token) {
		String[] arr = new String[] { token, signInfo.getTimestamp(), signInfo.getNonce() };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		content = null;
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return tmpStr != null ? tmpStr.equals(signInfo.getSignature().toUpperCase()) : false;
	}

	/**
	 * @Title: byteToStr
	 * @Description: byte转字符串
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * @Title: byteToStr
	 * @Description: 将字节转换为十六进制字符串
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {

		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}

	/**
	 * 微信JSAPI签名
	 * @param jsapiTicket
	 * @param url
	 * @return
	 */
	public static Map<String, String> jsApiSign(String jsapiTicket, String url, String appId) {
		Map<String, String> ret = new HashMap<String, String>();
		String nonce_str = UUID.randomUUID().toString().replaceAll("-","");
		String timestamp = String.valueOf(System.currentTimeMillis()/1000);
		String signature = "";
		//注意这里参数名必须全部小写，且必须有序
		String str = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		try{
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(str.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		}catch (NoSuchAlgorithmException e){
			e.printStackTrace();
		}catch (UnsupportedEncodingException e){
			e.printStackTrace();
		}
		ret.put("url", url);
		ret.put("jsapiTicket", jsapiTicket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		ret.put("appId",appId);
		return ret;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash){
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}
}
